package com.ibm.workplace.wcm.cqplugin.composites;

import java.util.List;

import org.eclipse.core.runtime.jobs.*;
import org.eclipse.jface.action.*;
import org.eclipse.jface.dialogs.*;
import org.eclipse.swt.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;

import com.ibm.workplace.wcm.cqplugin.*;
import com.ibm.workplace.wcm.cqplugin.cq.CqDefectInfo;
import com.ibm.workplace.wcm.cqplugin.cq.CqDefectQuery;
import com.ibm.workplace.wcm.cqplugin.cq.CqDefectSearchCriteria;
import com.ibm.workplace.wcm.cqplugin.cqweb.*;
import com.ibm.workplace.wcm.cqplugin.preference.BugInfoPreferenceConstants;
import com.ibm.workplace.wcm.cqplugin.ui.BugTable;
import com.ibm.workplace.wcm.cqplugin.ui.views.CQBugInfoView;

public class BugInfoViewComposite extends Composite implements SelectionListener, KeyListener, FocusListener{

    private Combo queryCombo = null;
    private ToolItem configureQueriesItem;
    private ToolItem refreshItem;
    private BugTable bugTable;
    private Text bugIdText = null;
    private Composite statusArea = null;
    private Label statusLabel = null;
    private ProgressBar progressBar = null;
    private Button stopButton = null;
    private Button goButton = null;

    private static final String QUICK_BUG_MESSAGE = "Type defect number";

    public BugInfoViewComposite(Composite parent, int style) {
        super(parent, style);

        initialize();

        //kevin populateQueryList();
    }

    private void initialize() {
        GridLayout gridLayout = new GridLayout();
        gridLayout.numColumns = 1;
        gridLayout.marginHeight = 0;
        gridLayout.marginWidth = 0;

        Composite c = new Composite(this, 0);
        c.setLayoutData(new GridData(GridData.FILL_BOTH));
        GridLayout layout2 = new GridLayout(3, false);
        layout2.marginHeight = 3;
        layout2.marginWidth = 3;
        c.setLayout(layout2);
        c.setBackground(c.getDisplay().getSystemColor(SWT.COLOR_WHITE));
        /*
        Label label = new Label(c, SWT.NONE);
        label.setText("Query:");
        label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
        */
        
        this.setLayout(gridLayout);
        
        //createQueryCombo(c);
        
        this.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
        
        /*
        ToolBar bar = new ToolBar(c, SWT.FLAT);
        bar.setBackground(c.getBackground());

        //do not have a query list now
        configureQueriesItem = new ToolItem(bar, SWT.FLAT);
        configureQueriesItem.setImage(BugInfoPluginActivator.getImage(BugInfoPluginActivator.IMAGE_QUERY));
        configureQueriesItem.addSelectionListener(this);
        configureQueriesItem.setToolTipText("Edit Queries");
        
        //do not have a refresh button
        refreshItem = new ToolItem(bar, SWT.FLAT);
        refreshItem.setImage(Activator.getImage(Activator.IMAGE_REFRESH));
        refreshItem.addSelectionListener(this);
        refreshItem.setToolTipText("Refresh");
		*/
        
        bugTable = new BugTable(c);
        GridData gridData2 = new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
        gridData2.horizontalSpan = 3;
        bugTable.setLayoutData(gridData2);

        Composite c3 = new Composite(c, 0);
        GridLayout layout3 = new GridLayout(2, false);
        layout3.marginWidth = 0;
        layout3.marginHeight = 0;
        c3.setLayout(layout3);
        c3.setBackground(c.getBackground());
        GridData gd4 = new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL);
        gd4.horizontalSpan = 4;
        c3.setLayoutData(gd4);
        
        // Kevin: Comment Out to avoid error
        //Label label1 = new Label(c3, SWT.NONE);
        //label1.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));        
        //label1.setImage(BugInfoPluginActivator.getImage(BugInfoPluginActivator.IMAGE_FIND));
        
        bugIdText = new Text(c3, SWT.BORDER);
        GridData gd3 = new GridData(GridData.FILL_HORIZONTAL);
        bugIdText.setLayoutData(gd3);
        bugIdText.addKeyListener(this);
        bugIdText.setText(QUICK_BUG_MESSAGE);
        bugIdText.addFocusListener(this);

        goButton = new Button(c3, SWT.PUSH);       
        goButton.setText("Go");
        goButton.addSelectionListener(this);
        
        statusArea = new Composite(c, 0);
        GridData data = new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL);
        data.horizontalSpan = 3;
        statusArea.setLayoutData(data);
        GridLayout layout = new GridLayout(3, false);
        layout.marginHeight = 0;
        statusArea.setLayout(layout);
        statusArea.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));

        statusLabel = new Label(statusArea, 0);
        statusLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL));
        statusLabel.setText("");
        statusLabel.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));

        progressBar = new ProgressBar(statusArea, SWT.BORDER | SWT.HORIZONTAL);
        progressBar.setMinimum(0);
        progressBar.setMaximum(100);
        data = new GridData(GridData.HORIZONTAL_ALIGN_END);
        data.widthHint = 50;
        progressBar.setLayoutData(data);
        progressBar.setVisible(false);

        stopButton = new Button(statusArea, SWT.PUSH);       
        stopButton.setImage(Activator.getImage(Activator.IMAGE_STOP));       
        stopButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END));
        stopButton.setVisible(false);
        stopButton.addSelectionListener(this);

        createMenuManager();

        /*        DragSource ds = new DragSource(bugTable, DND.DROP_MOVE| DND.DROP_COPY);
         ds.setTransfer(new Transfer[] {TextTransfer.getInstance()});
         ds.addDragListener(new DragSourceAdapter() {
         public void dragSetData(DragSourceEvent event) {
         event.data = new Object();
         System.out.println(event);
         StringBuffer sb = new StringBuffer();
         int columnCount = table.getColumnCount();
         TableItem[] items = table.getItems();
         int itemCount = items.length;
         if (items != null) {
         for (int i = 0; i < itemCount; ++i) {
         TableItem item = items[i];
         for (int j = 0; j < columnCount; ++j) {
         sb.append(item.getText(j));
         if (j != columnCount - 1) {
         sb.append("\t");
         }
         }
         if (i != itemCount - 1) {
         sb.append("\n");
         }
         }
         }
         vent.data = sb.toString(); 
         }

         public void dragStart(DragSourceEvent arg0) {
         arg0.data = this;
         }
         }); */
    }

    /**
     * This method initializes filterCombo	
     *
     */
    private void createQueryCombo(Composite parent) {
        GridData gridData2 = new GridData(GridData.GRAB_HORIZONTAL);
        gridData2.horizontalAlignment = GridData.FILL;
        gridData2.verticalAlignment = GridData.CENTER;
        queryCombo = new Combo(parent, SWT.READ_ONLY);
        queryCombo.setLayoutData(gridData2);
        queryCombo.addSelectionListener(this);
        queryCombo.setVisibleItemCount(10);
    }

    private void createMenuManager() {
        MenuManager mm = bugTable.getDefaultMenuManager();
        mm.add(new Separator());
        // Comment Out to avoid error
        /*
        mm.add(new ConfigureQueriesAction(bugTable.getTableViewer()));
        mm.add(new Separator());
        mm.add(new RefreshAction(bugTable.getTableViewer()));
        mm.add(new Separator());
        mm.add(new ShowAboutAction(getShell()));
		*/
        // Comment Out to avoid error
        bugTable.getTable().setMenu(mm.createContextMenu(bugTable.getTable()));
    }

    public void refresh() {
        if (!isDisposed() && bugTable.getTableViewer() != null) {
            bugTable.getTableViewer().refresh();
        }
    }

    public void populateQueryList() { //String selectedQuery) {
        if (!isDisposed() && queryCombo != null) {
            queryCombo.removeAll();

            // Comment Out to avoid error
            /*
            IBugQueryStore store = Activator.getDefault().getBugQueryStore();
            IBugQuery[] queries = store.loadQueries();
            if (queries != null) {
                for (int i = 0; i < queries.length; i++) {
                    queryCombo.add(queries[i].getName());
                }
            }
            
            queryCombo.setData(queries);
            */
        }
    }

    public void widgetDefaultSelected(SelectionEvent arg0) {

    }

    public void widgetSelected(SelectionEvent event) {
    	// Comment Out to avoid error
    	/*
    	if (event.getSource() == configureQueriesItem) {
            ConfigureQueriesAction action = new ConfigureQueriesAction(bugTable.getTableViewer());
            action.run();
        } else if (event.getSource() == queryCombo) {
            int index = queryCombo.getSelectionIndex();
            selectQuery(index);
        } else if (event.getSource() == stopButton) {
            Job job = CQBugInfoView.getInstance().getCurrentBugSearchJob();
            if (job != null) {
                job.cancel();
                setProgressStatusText("Search aborted. Please wait...");
                stopButton.setEnabled(false);
            }
        } else if (event.getSource() == refreshItem) {
            RefreshAction refreshAction = new RefreshAction(bugTable.getTableViewer());
            refreshAction.run();
        }
        */
    	if (event.getSource() == goButton) {
    		startQueryById();
        }
    }

    public void selectQuery(String name) {
        int selectionIndex = -1;
        
        // Comment Out to avoid error
        /*
        if (name != null) {
            IBugQuery[] queries = (IBugQuery[]) queryCombo.getData();
            if (queries != null) {
                for (int i = 0; i < queries.length; i++) {
                    if (queries[i].getName() != null && queries[i].getName().trim().equals(name)) {
                        selectionIndex = i;
                        break;
                    }
                }
            }
        }
		*/
        if (selectionIndex != -1) {
            selectQuery(selectionIndex);
        }
    }

    public void selectQuery(int index) {
        if (index >= 0 && index < queryCombo.getItemCount()) {
            queryCombo.select(index);
            // Comment Out to avoid error
            /*
            final IBugQuery query = ((IBugQuery[]) queryCombo.getData())[index];
            CQBugInfoView.getInstance().performSearch(query);

            BugInfoPluginActivator.getDefault().getPreferenceStore().setValue(BugInfoPreferenceConstants.PREF_PREVIOUS_QUERY, query.getName());
            */
        }
    }

    public void focusGained(FocusEvent event) {
        if (event.getSource() == bugIdText && bugIdText.getText().equals(QUICK_BUG_MESSAGE)) {
            bugIdText.setText("");
        } else {
            bugIdText.selectAll();
        }
    }

    public void focusLost(FocusEvent event) {
        if (event.getSource() == bugIdText && bugIdText.getText().trim().equals("")) {
            bugIdText.setText(QUICK_BUG_MESSAGE);
        }
    }

    public void keyPressed(KeyEvent arg0) {
    	if(Activator.DEBUG_ON)
    		System.out.println("keyPressed()");
        if (arg0.keyCode == 13) {
        	if(Activator.DEBUG_ON)
        		System.out.println("keyPressed() if");
        	startQueryById();
        }
    }

    public void keyReleased(KeyEvent arg0) {

    }
    
    private void startQueryById() {
    	bugIdText.setEditable(false);
    	goButton.setEnabled(false);
    	
    	final String defectNumber = bugIdText.getText().trim();
        if (defectNumber.trim().equals("")) {
            MessageDialog.openError(getShell(), "Error", "You must supply a valid bug number.");
            return;
        }
        if(Activator.DEBUG_ON)
        	System.out.println("keyPressed() if 1");
        CqDefectQuery query = new CqDefectQuery(new CqDefectSearchCriteria(defectNumber));
        if(Activator.DEBUG_ON)
        	System.out.println("keyPressed() if 2");
        //queryCombo.deselectAll();
        if(Activator.DEBUG_ON)
        	System.out.println("keyPressed() if 3");
        bugTable.getTableViewer().setInput(null);
        
        if(Activator.DEBUG_ON)
        	System.out.println("about to enter performSearch()");
        CQBugInfoView.getInstance().performSearch(query);
    }
    
    // Comment Out to avoid error

    public void bugSearchComplete(IBugSearchResults searchResults) {
    	if(Activator.DEBUG_ON)
    		System.out.println("bugSearchComplete 1");
        IBugInfo[] bugs = searchResults.getResults();
        if(Activator.DEBUG_ON)
        	System.out.println("bugSearchComplete 2");
        bugTable.getTableViewer().setInput(bugs);
        if(Activator.DEBUG_ON)
        	System.out.println("bugSearchComplete 3");
        bugTable.getTableViewer().setData(IBugQuery.class.getName(), searchResults.getQuery());

        if (bugs != null) {
        	if(Activator.DEBUG_ON)
        		System.out.println("bugs != null");
            if (bugs.length != 1) {
            	if(Activator.DEBUG_ON)
            		System.out.println("bugs.length != 1");
                setProgressStatusText(bugs.length + " defects found" + (searchResults.getSearchTime() > 0 ? " (" + searchResults.getSearchTime() + " ms)." : "."));
            } else {
            	if(Activator.DEBUG_ON)
            		System.out.println("bugs.length == 1");
                setProgressStatusText("1 defect found.");
            }
        }
        
        bugIdText.setEditable(true);
        goButton.setEnabled(true);
        //kevin setProgressVisible(false);

        try {
            //tableViewer.getTable().setFocus();
        } catch (Exception ex) {
            // ex.printStackTrace();
        }
    }


    public void setProgressStatusText(final String text) {
        if (Thread.currentThread() != Display.getDefault().getThread()) {
            Display.getDefault().asyncExec(new Runnable() {
                public void run() {
                    statusLabel.setText(text == null ? "" : text);
                }
            });
        } else {
            statusLabel.setText(text == null ? "" : text);
        }
    }

    public void setProgressVisible(final boolean visible) {
        if (Thread.currentThread() != Display.getDefault().getThread()) {
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    progressBar.setSelection(0);
                    progressBar.setVisible(visible);
                    stopButton.setVisible(visible);
                    stopButton.setEnabled(true);
                }
            });
        } else {
            progressBar.setSelection(0);
            progressBar.setVisible(visible);
            stopButton.setVisible(visible);
            stopButton.setEnabled(true); // this feels hacky!!!
        }
    }

    public void setProgress(final int percent) {
    	if(Activator.DEBUG_ON)
    		System.out.println("precent: " + percent);
        if (Thread.currentThread() != Display.getDefault().getThread()) {
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    progressBar.setSelection(percent);
                    progressBar.redraw();
                }
            });
        } else {
            progressBar.setSelection(percent);
        }
    }

    public void cancelProgress() {
        if (Thread.currentThread() != Display.getDefault().getThread()) {
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    progressBar.setVisible(false);
                }
            });
        } else {
            progressBar.setVisible(false);
        }
    }

}
